package com.ttc.mBackupK16.BackupPhotos;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class Zipper extends AsyncTask<Void, String, String> {

	private ArrayList<String> filesToZip;
	
	private String zipFileName;
	private String zipFile;
	private ProgressDialog mProgress;
	int currentProcess;
	private Context context;
	private String currentStatus = "Zipping images....";
	public boolean isFinished = false;

	public Zipper( ArrayList<String> filesToZip,
			String zipFileName) {
			
		this.filesToZip = filesToZip;		
		this.zipFileName = zipFileName;

	}
	
	@Override
	protected String doInBackground(Void... params) {
		String result = "";
		zipFileName +=".zip";
		try {

			String root = Environment.getExternalStorageDirectory().toString();
			String zipFile = root + "/mBackup";

			File dir = new File(zipFile);
			if (!dir.exists())
				dir.mkdirs();

			zipFile = zipFile + "/" + zipFileName;

			Log.i("mediastore", "ZIPFILE: " + zipFile);
			byte[] buffer = new byte[1024];

			File f = new File(zipFile);
			// if (f.delete() == true)
			// Log.v("mediastore", "Deleted");
			if (!f.exists())
				f.createNewFile();

			FileOutputStream fout = new FileOutputStream(f);

			ZipOutputStream zout = new ZipOutputStream(fout);
			// zout.setLevel(6);

			int n = filesToZip.size();
			FileInputStream fin;
			ZipEntry zipEntry;
			for (int i = 0; i < n; i++) {

				fin = new FileInputStream(filesToZip.get(i));
				zipEntry = new ZipEntry(filesToZip.get(i));

				zout.putNextEntry(zipEntry);

				int length;

				while ((length = fin.read(buffer)) > 0) {
					zout.write(buffer, 0, length);
				}

				zout.closeEntry();
				fin.close();

				// update process
				currentProcess = i + 1;

				String filePath = zipEntry.getName();
				String fileName = filePath.substring(
						filePath.lastIndexOf("/") + 1, filePath.length());

				currentStatus = "Adding: " + fileName;
				publishProgress(new String[] { "Adding: " + fileName });
			}

			// close the ZipOutputStream
			publishProgress(new String[] { "Saving backup file..." });
			zout.flush();
			zout.close();

			result = "Finished";
		} catch (IOException ioe) {
			Log.v("mediastore",
					"Error at ZipFlie.doinBackGround: " + ioe.getMessage());
			result = "Error";
			//FileManager.deleteFile(zipFile);
			if (mProgress != null) {
				mProgress.dismiss();
				mProgress = null;
			}
		}
		return result;
	}

	
	
	
	@Override
	protected void onPreExecute() {
		showProgress();
		super.onPreExecute();
	}

	@Override
	protected void onPostExecute(String result) {
		isFinished = true;
		Toast.makeText(context, "Finished", Toast.LENGTH_SHORT).show();
		if (mProgress != null) {
			mProgress.dismiss();
			mProgress = null;
		}
		super.onPostExecute(result);
	}

	@Override
	protected void onProgressUpdate(String... values) {
		mProgress.setMessage(values[0]);
		mProgress.setProgress(currentProcess);
		super.onProgressUpdate(values);
	}
	
	private void showProgress(){
		try{
			mProgress = new ProgressDialog(context.getApplicationContext());
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setMessage(currentStatus);
			mProgress.setCancelable(true);
			mProgress.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					cancel(true);		

				}
			});
			mProgress.setMax(filesToZip.size()-1);
			mProgress.show();
			mProgress.setProgress(currentProcess);
			
			}catch (Exception e) {
				Log.e("mediastore", "Error at ZipFileProcess.ShowProgress: " + e.getMessage());
			}			
	}

}
